"""
管理员用户管理API
"""
from fastapi import APIRouter, HTTPException, status, Depends, Request
from typing import Optional
from models.m import AdminUser, Role, OperationLog
from schemas.admin_schemas import (
    AdminUserCreate, AdminUserUpdate, AdminUserResponse,
    ResponseModel, PageResponse, PageRequest, ChangePasswordRequest
)
from utils.auth_middleware import get_current_user, check_permission
from utils.password_utils import hash_password, verify_password
from tortoise.expressions import Q


admin_user_router = APIRouter(prefix="/admin/users", tags=["管理员用户管理"])


@admin_user_router.get("", response_model=ResponseModel, summary="获取管理员列表（分页）")
async def get_admin_users(
    page: int = 1,
    page_size: int = 10,
    keyword: Optional[str] = None,
    role_id: Optional[int] = None,
    status: Optional[int] = None,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    获取管理员列表（支持分页、搜索、筛选）
    """
    # 权限检查
    # if not await check_permission(request, "admin_user:list"):
    #     raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="无权限")
    
    # 构建查询条件
    query = AdminUser.all()
    
    if keyword:
        query = query.filter(
            Q(username__icontains=keyword) | 
            Q(real_name__icontains=keyword) |
            Q(email__icontains=keyword) |
            Q(phone__icontains=keyword)
        )
    
    if role_id is not None:
        query = query.filter(role_id=role_id)
    
    if status is not None:
        query = query.filter(status=status)
    
    # 统计总数
    total = await query.count()
    
    # 分页查询
    offset = (page - 1) * page_size
    users = await query.offset(offset).limit(page_size).prefetch_related('role')
    
    # 组装响应数据
    items = []
    for user in users:
        items.append({
            "id": user.id,
            "username": user.username,
            "real_name": user.real_name,
            "email": user.email,
            "phone": user.phone,
            "avatar": user.avatar,
            "status": user.status,
            "last_login_time": user.last_login_time.isoformat() if user.last_login_time else None,
            "last_login_ip": user.last_login_ip,
            "role_id": user.role.id if user.role else None,
            "role_name": user.role.name if user.role else None,
            "create_time": user.create_time.isoformat(),
            "update_time": user.update_time.isoformat(),
        })
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "total": total,
            "page": page,
            "page_size": page_size,
            "items": items
        }
    }


@admin_user_router.get("/{user_id}", response_model=ResponseModel, summary="获取管理员详情")
async def get_admin_user(
    user_id: int,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    获取指定管理员的详细信息
    """
    user = await AdminUser.get_or_none(id=user_id).prefetch_related('role')
    
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "id": user.id,
            "username": user.username,
            "real_name": user.real_name,
            "email": user.email,
            "phone": user.phone,
            "avatar": user.avatar,
            "status": user.status,
            "last_login_time": user.last_login_time.isoformat() if user.last_login_time else None,
            "last_login_ip": user.last_login_ip,
            "role_id": user.role.id if user.role else None,
            "role_name": user.role.name if user.role else None,
            "create_time": user.create_time.isoformat(),
            "update_time": user.update_time.isoformat(),
        }
    }


@admin_user_router.post("", response_model=ResponseModel, summary="创建管理员")
async def create_admin_user(
    request: Request,
    user_data: AdminUserCreate,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    创建新的管理员用户
    """
    # 检查用户名是否已存在
    existing_user = await AdminUser.get_or_none(username=user_data.username)
    if existing_user:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="用户名已存在")
    
    # 检查角色是否存在
    role = await Role.get_or_none(id=user_data.role_id)
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
    
    # 加密密码
    hashed_password = hash_password(user_data.password)
    
    # 创建用户
    user = await AdminUser.create(
        username=user_data.username,
        password=hashed_password,
        real_name=user_data.real_name,
        email=user_data.email,
        phone=user_data.phone,
        status=user_data.status,
        role_id=user_data.role_id
    )
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="create_admin_user",
        module="管理员管理",
        description=f"创建管理员: {user.username}",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        request_data=user_data.model_dump(exclude={'password'}),
        status=1
    )
    
    return {
        "code": 200,
        "message": "创建成功",
        "data": {"id": user.id}
    }


@admin_user_router.put("/{user_id}", response_model=ResponseModel, summary="更新管理员")
async def update_admin_user(
    request: Request,
    user_id: int,
    user_data: AdminUserUpdate,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    更新管理员信息
    """
    user = await AdminUser.get_or_none(id=user_id)
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
    
    # 如果修改角色，检查角色是否存在
    if user_data.role_id is not None:
        role = await Role.get_or_none(id=user_data.role_id)
        if not role:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
        user.role_id = user_data.role_id
    
    # 更新字段
    if user_data.real_name is not None:
        user.real_name = user_data.real_name
    if user_data.email is not None:
        user.email = user_data.email
    if user_data.phone is not None:
        user.phone = user_data.phone
    if user_data.avatar is not None:
        user.avatar = user_data.avatar
    if user_data.status is not None:
        user.status = user_data.status
    
    await user.save()
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="update_admin_user",
        module="管理员管理",
        description=f"更新管理员: {user.username}",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        request_data=user_data.model_dump(exclude_none=True),
        status=1
    )
    
    return {
        "code": 200,
        "message": "更新成功",
        "data": None
    }


@admin_user_router.delete("/{user_id}", response_model=ResponseModel, summary="删除管理员")
async def delete_admin_user(
    request: Request,
    user_id: int,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    删除管理员（软删除，设置状态为禁用）
    """
    user = await AdminUser.get_or_none(id=user_id)
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
    
    # 不能删除自己
    if user.id == current_user.id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="不能删除自己")
    
    # 软删除（设置状态为禁用）
    user.status = 0
    await user.save()
    
    # 如果需要物理删除，使用：await user.delete()
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="delete_admin_user",
        module="管理员管理",
        description=f"删除管理员: {user.username}",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        status=1
    )
    
    return {
        "code": 200,
        "message": "删除成功",
        "data": None
    }


@admin_user_router.post("/change-password", response_model=ResponseModel, summary="修改密码")
async def change_password(
    request: Request,
    password_data: ChangePasswordRequest,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    修改当前用户密码
    """
    # 验证旧密码
    if not verify_password(password_data.old_password, current_user.password):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="旧密码错误")
    
    # 加密新密码
    new_hashed_password = hash_password(password_data.new_password)
    
    # 更新密码
    current_user.password = new_hashed_password
    await current_user.save()
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="change_password",
        module="管理员管理",
        description=f"修改密码",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        status=1
    )
    
    return {
        "code": 200,
        "message": "密码修改成功",
        "data": None
    }


@admin_user_router.post("/{user_id}/reset-password", response_model=ResponseModel, summary="重置密码")
async def reset_password(
    request: Request,
    user_id: int,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    重置指定用户的密码为默认密码：123456
    """
    user = await AdminUser.get_or_none(id=user_id)
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
    
    # 重置为默认密码
    default_password = "123456"
    user.password = hash_password(default_password)
    await user.save()
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="reset_password",
        module="管理员管理",
        description=f"重置管理员密码: {user.username}",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        status=1
    )
    
    return {
        "code": 200,
        "message": f"密码已重置为：{default_password}",
        "data": None
    }

